package com.fingard.dsp.bank.directbank.ynht01;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2019/3/12.
 */
public class YNHT01Transaction extends YNHT01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAtsTrans.writeStart();

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                YNHT01Header header = new YNHT01Header();
                header.tranCode = "500002";
                Date date = new Date();
                header.termDate = Format.Date8Format.format(date);
                header.termTime = Format.Time6Format.format(date);
                header.seqNo = getQryTransID();
                writeCommonHeader(xmlTextWriter, header);
                xmlTextWriter.writeStartElement("ReqParam");
//                < AcctNo >账号</ AcctNo >
                xmlTextWriter.writeElementString("AcctNo", p_req7516.actNum);
//                < BeginDate >起始日期</ BeginDate >
                xmlTextWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
//                < EndDate >终止日期</ EndDate >
                xmlTextWriter.writeElementString("EndDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                xmlTextWriter.writeEndDocument();
                String[] resutlt = sendToBank(xmlTextWriter.toXmlString());
                if (resutlt[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].trim(), tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/HTBankData/RspData/RspHead/RspCode");
                        String returnMsg = tmpBkReader.getFirstText("/HTBankData/RspData/RspHead/RspMsg");
                        if ("000000".equals(returnCode)) {
                            String fileName = tmpBkReader.getFirstText("/HTBankData/RspData/Result/FileName");

                            String localhostSavePath = createTempFileDirectory() + File.separator + "transaction";
                            File mdDir = new File(localhostSavePath);
                            if (!mdDir.exists()) {
                                mdDir.mkdirs();
                            }
                            WriteBankLogLn2("明细文件保存本地路径: " + localhostSavePath);
                            FileHelper.mkdir(localhostSavePath);
                            FtpSet ftpSet = bankFront.getFtpSet("transaction");

                            String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + fileName;
                            WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                            SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                            FtpReceiver receiver = sftpPortClient.downloadFile("", sftpFilePath, localhostSavePath);
//                                sftpPortClient.disconnect();
//                                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
//                                FtpReceiver receiver = sftpPortClient.downloadFileByName("",localhostSavePath,fileName);
                            sftpPortClient.disconnect();
                            if (receiver.isCompleted) {
                                String transContent = FileHelper.readFileText(localhostSavePath +
                                        File.separator + fileName, ftpSet.charset);
                                if (StringHelper.hasAnyChar(transContent)) {
                                    String[] transDetailArr = transContent.split("\\n");
                                    for (String transDetail : transDetailArr) {
                                        //为避免末尾全为分隔符导致数组解析有误，在末位加上自定义的一个字符"+",确保所有的分隔符都解析到位
                                        transDetail = transDetail + "+";
                                        String[] tranInfos = transDetail.split("\\|!");
                                        RetAtsTransDetail detail = new RetAtsTransDetail();
//                                            AcctNo	帐号	32
                                        detail.actNum = tranInfos[0];
//                                            TranDate	交易日期	8		YYYYMMDD
//                                            TranTime	交易时间	6		HHMMSS
                                        detail.tranDate = DateHelper.convertD8toD10(tranInfos[1]);
                                        detail.valueDate = detail.tranDate;
                                        detail.tranTime = detail.tranDate + " " + tranInfos[2].substring(0, 2) + ":" +
                                                tranInfos[2].substring(2, 4) + ":" + tranInfos[2].substring(4, 6);
//                                            TranAmt	交易金额	17，2  3
                                        detail.tranAmt = tranInfos[3];
//                                            Balance	账户余额	17，2
                                        detail.accBal = tranInfos[4];
//                                            AcctNo1	对方账号	32
                                        detail.recAccNum = tranInfos[5];
//                                            AcctName1	对方账户名称	70    6
                                        detail.recAccName = tranInfos[6];
//                                            Abstract	摘要信息	20
                                        detail.usage = tranInfos[7];
//                                            DCFlag	借贷方向	1		0-借 1-贷
                                        //DSP:1-借，2-贷
                                        if (tranInfos[8].equals("1")) {
                                            if (detail.tranAmt.indexOf("-") >= 0) {
                                                detail.cdFlag = "1";
                                                detail.tranAmt = detail.tranAmt.substring(1);
                                            } else {
                                                detail.cdFlag = "2";
                                            }
                                        } else if (tranInfos[8].equals("0")) {
                                            if (detail.tranAmt.indexOf("-") >= 0) {
                                                detail.cdFlag = "2";
                                                detail.tranAmt = detail.tranAmt.substring(1);
                                            } else {
                                                detail.cdFlag = "1";
                                            }
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "借贷标志( " + tranInfos[8] + ")无法识别，请与银行核对";
                                            break;
                                        }
//                                            SeqNo	流水号	34
//                                            CertNo	凭证号	32
                                        detail.urid = tranInfos[9];//流水号
                                        detail.abstr = tranInfos[10];//凭证号
                                        detail.recAccBank = tranInfos[12];//对方银行名

                                        retAtsTrans.writeRetDetail(detail);
                                    }
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = "获取文件失败";
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = returnMsg;
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = resutlt[1];
                    break;
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
